// /store/cart.js


export default {
  namespaced: true,
  state: {
    items: uni.getStorageSync('cart_items') || [],
    total: uni.getStorageSync('cart_total') || 0,
	orderAddress:[],
	lastAddress:{}
  },
  mutations: {
    addItem(state, product) {
      const exist = state.items.find(item => item._id === product._id)
      if (exist) {
        exist.quantity++
      } else {
        state.items.push({
          ...product,
          quantity: 1,
          selected: true
        })
      }
      this.commit('cart/saveToStorage')
    },
	SET_orderAddress(state,res){
		state.orderAddress=res
	},
    SET_lastAddress(state,res){
		state.lastAddress=res
	},
    removeItem(state, id) {
      state.items = state.items.filter(item => item._id !== id)
      this.commit('cart/saveToStorage')
    },
    updateQuantity(state, { id, quantity }) {
      const item = state.items.find(item => item._id === id)
      if (item) {
        item.quantity = quantity
        this.commit('cart/saveToStorage')
      }
    },
    saveToStorage(state) {
      uni.setStorageSync('cart_items', state.items)
      state.total = state.items.reduce((sum, item) => sum + (item.price * item.quantity), 0)
      uni.setStorageSync('cart_total', state.total)
    },
    clearCart(state) {
      state.items = []
      state.total = 0
      uni.removeStorageSync('cart_items')
      uni.removeStorageSync('cart_total')
    }
  },
  getters: {
    totalCount: state => state.items.reduce((sum, item) => sum + item.quantity, 0),
	getCart:state=>state.items.length||0
  }
}

